<template>
    <view class="page-body">
        <view class="page-body-box">
            <view class="buyinfo-box">
                <view class="buyinfo-row-text">产品名称</view>
                <view class="buyinfo-row-input" @tap="openGoodsPicker">
                    <view class="buyinfo-row-input-text">{{data.goodsName}}</view>
                    <image src="../../static/ibs/img_comm_skip.png" mode=""></image>
                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text">国　　家</view>
                <view class="buyinfo-row-input" @tap="openCountryPicker">
                    <view class="buyinfo-row-input-text">{{data.countryOrigin}}</view>
                    <image src="../../static/ibs/img_comm_skip.png" mode=""></image>
                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text">意向价格</view>
                <view class="buyinfo-row2-input"><input type="input" id="lowesPrice" maxlength="6" class="buyinfo-row2-text" v-model="data.intentPriceBottom"
                                                        placeholder="最低" placeholder-class="textarea-placeholder" @blur="checkInput" />
                    <text class="buyinfo-row2-text-line">~</text>
                    <input type="input" id="highestPrice" v-model="data.intentPriceTop" maxlength="6" class="buyinfo-row2-text" placeholder="最高"
                           placeholder-class="textarea-placeholder" @blur="checkInput"/>
                    <text class="buyinfo-row2-text-pro">RMB/KG</text>
                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text">厂　　号</view>
                <view class="buyinfo-row-input" @tap="openVendorPicker()">
                    <view class="buyinfo-row-input-text">
                        <text v-if="data.vendorNo==''" class="select-default">选填</text>
                        {{data.vendorNo}}
                    </view>
                    <image src="../../static/ibs/img_comm_skip.png" mode=""></image>
                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text letter-spacing">接  货  地</view>
                <view class="buyinfo-row-input" @tap="openCityPicker()">
                    <view class="buyinfo-row-input-text">
                        <text v-if="data.city==''" class="select-default">选填</text>
                        {{data.city}}
                    </view>
                    <image src="../../static/ibs/img_comm_skip.png" mode=""></image>
                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text letter-spacing">求  购  量</view>
                <view class="buyinfo-row-input">
                    <view class="buyinfo-row-input-text">
                        <input class="buyinfo-row-input-text-input" maxlength="8" placeholder-class="textarea-placeholder" type="input"
                               placeholder="选填"  id='weight' v-model="data.weight" @blur="checkInput"/></view>
                    <text class="buyinfo-row-input-unit">吨</text>

                </view>
            </view>
            <view class="buyinfo-box">
                <view class="buyinfo-row-text">要　　求</view>
                <view class="buyinfo-row-textarea">
                    <textarea v-model="data.remarkDemand"    placeholder="选填"
                              placeholder-class="textarea-placeholder"  maxlength="40" v-if="!isShowGoodsPicker && !isShowCountryPicker && !isShowVendorPicker && !isShowCityPicker"/>
                </view>
            </view>
            <view class="buyinfo-checkbox" @tap="onCheckbox">
                <view class="buyinfo-checkbox-btn" >
                    <image v-if="!isCheckbox" src="../../static/ibs/img_comm_check_n.png" mode=""></image>
                    <image v-if="isCheckbox" src="../../static/ibs/img_comm_check.png" mode=""></image>
                </view>
                <text class="buyinfo-checkbox-line16">请确认您发布的求购是符合中国相关法律的正关产品，否则您可能承担相应法律责任</text>
            </view>
            <wx-form-id :saveData="saveBuyInfo" :getFormId="saveFormId"
                        :btnClass="btnClass" :btnSubmitClass="btnSubmitClass" :btnName="optionLabel"></wx-form-id>
            <!--            <view class="buyinfo-btn-box">
                            <button type="" @tap="saveBuyInfo">{{optionLabel}}</button>

                        </view> -->
            <nested-picker v-if="isShowGoodsPicker" @close="closeGoodsPicker" :levelData="goodsPickerData"
                           @sure="selectedGoods" title="选择产品名称" firstLevelPropertyName="goodsNameCn"
                           :firstLevelSelected="data.goodsName"></nested-picker>
            <nested-picker v-if="isShowCountryPicker" @close="closeCountryPicker" :levelData="vendorPickerData"
                           @sure="selectedCountry" title="选择国家" firstLevelPropertyName="countryOrigin"
                           :firstLevelSelected="data.countryOrigin"></nested-picker>
            <nested-picker v-if="isShowVendorPicker" @close="closeVendorPicker" :levelData="vendorPickerData"
                           @sure="selectedVendor" title="选择产地厂号" firstLevelPropertyName="countryOrigin"
                           secondLevelPropertyName="vendorNo" nestedPropertyName="vendorVos"
                           :firstLevelSelected="data.countryOrigin" :secondLevelSelected="data.vendorNo"></nested-picker>
            <nested-picker v-if="isShowCityPicker" @close="closeCityPicker" :levelData="cityPickerData"
                           @sure="selectedCity" title="选择存放地" firstLevelPropertyName="nodeName"
                           secondLevelPropertyName="nodeName" nestedPropertyName="children"
                           :firstLevelSelected="data.province" :secondLevelSelected="data.city"></nested-picker>
        </view>
    </view>
</template>
<script>
  import api from '@/common/api.js';   //请求API方法
  import sysEnum from '../../common/sysEnum.js';
  import publicMethod from '../../common/publicMethod.js';
  import nestedPicker from '@/components/form/nestedPicker.vue';
  import validate from "@/common/graceChecker.js";
  import wxFormId from '@/components/wxFromId.vue';
  export default {
    components: {
      nestedPicker,
      wxFormId
    },
    onPullDownRefresh() {
      this.noData = false;
      this.loadingType = 0;
      this.getData();
    },
    onReachBottom() {
      console.log("刷新");
      if (this.loadingType !== 0) {
        return;
      }
      this.loadingType = 1;
      setTimeout(() => {
        this.addData();
      }, 1200);
    },
    data() {
      return {
        optionLabel: '免费发布',    //按钮标签名字
        isShowGoodsPicker: false,   //产品名称弹出层标识
        isShowCountryPicker: false, //国家弹出层标识
        isShowVendorPicker: false,  //厂号弹出层标识
        isShowCityPicker: false,    //城市弹出层标识
        goodsClassNameArr: [],      //产品大类名称数组
        goodsClassName: '',         //产品大类名称
        //    goodsClass: null,
        goodsNameCn: '',            //产品中文名称
        countryOriginArr: [],
        countryOrigin: '',
        countryOriginClassName: null,
        vendorNoArr: [],
        vendorNo: '',
        storageProvince: '',
        storageCityArr: ['北京', '天津'],
        storageCity: '',
        productDate: '',
		lengths:0,
        isCheckbox: false,  //复选框标识
        goodsPickerData: null,
        vendorPickerData: null,
        cityPickerData: null,
        btnClass:['page-userinfo-btn-box'],
        btnSubmitClass:['page-userinfo-btn-submit-box'],
        data: {
          goodsName: '',
          countryOrigin: '',
          intentPriceBottom: '',
          intentPriceTop: '',
          vendorNo: '',
          province: '',
          city: '',
          weight: '',
          remarkDemand: ''
        },
        url: '/wechat/demand/saveDemand', // 接口地址
        navigatorUrl: '/pages/demand/index',
        successMessage: '发布求购成功！'
      };
    },
    onLoad(option) {
      let that = this;
      // 编辑我的求购
      if (option && option.id) {
        uni.setNavigationBarTitle({
          title: '编辑求购'
        });
        //uni.setNavigationBarTitle('编辑求购');
        that.optionLabel = '保存';
        that.getDemandData(option.id);
        that.url = '/wechat/user/editDemand';
        that.successMessage = '保存成功';
        that.navigatorUrl = '/pages/my/buyList';
        that.isCheckbox=true;
      }
      that.initData(); //初始化数据
    },
    //页面滚动事件
    methods: {

      async initData() {
        var that = this;
        //	that.companyName = this.userInfo.companyName;
        // 检查本地缓存中的基础数据是否为空
        if (uni.getStorageSync('base_goods') !== ''
            && uni.getStorageSync('base_city') !== ''
            && uni.getStorageSync('base_vendor') !== '') {
          that.handleInitData();// 自定义设置数据
          return; // 不为空的情况下使用本地缓存数据，不请求接口
        }
        // 调用请求数据方法
        var url = "/wechat/base/getBaseData";   //请求的URL
        var params = {};
        await api.httpRequest(url, params, "GET",true).then((res) => {
          // console.log(res);
          uni.setStorageSync('base_goods', res.result.goodsVo);
          uni.setStorageSync('base_city', res.result.treeNodeList);
          uni.setStorageSync('base_vendor', res.result.vendorVo);
          that.handleInitData(); // 自定义设置数据
        });
      },
      handleInitData() {
        let that = this;
        that.goodsPickerData = uni.getStorageSync('base_goods')[0].goodsVos;
        //以下代码暂用不上，目前产品名称只有一种，代码暂保留

          /* 				var baseGoods = uni.getStorageSync('base_goods');
           var goodsLen = baseGoods.length;
           if (goodsLen > 0) {
           baseGoods.forEach(function (item, index) {
           that.goodsClassNameArr.push(item.goodsClassName);
           })
           } */

        var baseVendor = uni.getStorageSync('base_vendor');
        that.vendorPickerData = uni.getStorageSync('base_vendor');
        console.log("vendor-----------", that.vendorPickerData)
        var vendorLen = baseVendor.length;
        if (vendorLen > 0) {
          baseVendor.forEach(function (item, index) {
            that.countryOriginArr.push(item.countryOrigin);
          })
        }
        that.cityPickerData = uni.getStorageSync('base_city');
      },

      //保存求购信息
      saveBuyInfo(getData) {
        var that = this;
       if (!validate.stringIsNullOrEmpty(that.data.intentPriceBottom) && !validate.stringIsNullOrEmpty(that.data.intentPriceTop)){
		   if (that.data.intentPriceBottom > that.data.intentPriceTop ){
		   			 that.showToast('最低意向价不能大于最高意向价');
		   			 return;
		   }
	   }
	   if (validate.stringIsNullOrEmpty(that.data.intentPriceBottom) && validate.stringIsNullOrEmpty(that.data.intentPriceTop)){
		   that.showToast('请填写意向价格');
		   return;
	   }
		let validateInput = that.checkData();
        if (!validateInput) {
          return;
        }
//				var url="/wechat/demand/saveDemand";   //请求地址
        var params = that.data;
        api.httpRequest(this.url, params, "POST",true).then((res) => {
          if (res.code == 200) {
            that.clearData();
            console.log("--------------------",that.navigatorUrl);
            if(that.navigatorUrl == '/pages/my/buyList'){
                var pages = getCurrentPages();
                let page = pages[pages.length - 2];
                uni.navigateBack({
                    delta: 1,
                    success:function() {
                        // 返回成功后重新加载页面
                        if (page == undefined || page == null) return;
                        page.onLoad();
                    }
                });
              /*uni.navigateTo({
                url: that.navigatorUrl,
                success: function () {
                  that.showToast(that.successMessage);
                }
              });*/
            }else if(that.navigatorUrl == '/pages/demand/index'){
              uni.switchTab({
                url: that.navigatorUrl,
                success: function () {
                  that.showToast(that.successMessage);
                }
              });
            }

          } else {
            uni.showToast({
              icon: 'none',
              title: res.message
            })
          }

        });
        that.isShowInfoBox = false;
      },
      /**
       * 根据求购的id获取发布的求购信息
       * @param id 求购ID
       **/
      getDemandData(id) {
        api.httpRequest('/wechat/user/detail/' + id, null, 'GET', true).then((res) => {
          if (res.code === 200) {
            this.data = res.result;
          } else {
            this.showToast(res.message);
          }
        });
      },
      //提交检查输入
      checkData() {
        if (validate.stringIsNullOrEmpty(this.data.goodsName)) {
          uni.showToast({
            icon: 'none',
            title: '产品名称不能为空'
          })
          return false;
        }
        if (validate.stringIsNullOrEmpty(this.data.countryOrigin)) {
          uni.showToast({
            icon: 'none',
            title: '国家不能为空'
          })
          return false;
        }
//        if (validate.stringIsNullOrEmpty(this.data.intentPriceBottom) || validate.stringIsNullOrEmpty(this.data.intentPriceTop)) {
//          this.showToast('意向价格不能为空');
//          return false;
//        }
          /*if(this.data.intentPriceTop =='' || this.data.intentPriceTop == undefined){
           uni.showToast({
           icon:'none',
           title:'最高价格不能为空'
           })
           return false;
           }*/
        if (!this.isCheckbox) {
          uni.showToast({
            icon: 'none',
            title: '请确认本次发布的求购信息符合国家法律法规'
          })
          return false;
        }
        return true;
      },
	  checkInput(e,type){
	      var value = e.detail.value
	      value = value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
	      value = value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的
	      value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
	      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
	      if(value.indexOf(".")< 0 && value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
	          if(value.substr(0,1)=='0'){
	              value = value.substr(1);
	          }
	          // value= parseFloat(value);
	      }
	      if(Number(value) === 0){
	          value= '';
	      }
		  if(e.currentTarget.id=== 'lowesPrice'){
			this.data.intentPriceBottom = value;
		  }
		  if(e.currentTarget.id === 'highestPrice'){
		  	this.data.intentPriceTop = value;
		  }
		  if(e.currentTarget.id === 'weight'){
		  	this.data.weight = value;
		  }
	      return {
	          value: value,
	      }
	  },
      // 品类名称二级选择控件
      openGoodsPicker() {
        this.isShowGoodsPicker = true;
      },
      closeGoodsPicker() {
        this.isShowGoodsPicker = false;
      },
      selectedGoods(goodsClassName, goodsNameCn) {
        this.goodsClassName = goodsClassName;
        console.log("goodsClassName====", goodsClassName)
        this.data.goodsName = goodsNameCn;
      },
      //打开国家
      openCountryPicker() {
        this.isShowCountryPicker = true;
      },
      closeCountryPicker() {
        this.isShowCountryPicker = false;
      },
      selectedCountry(countryOriginClassName, countryOrigin) {
        this.countryOriginClassName = countryOriginClassName;
        this.data.countryOrigin = countryOrigin;
		this.data.vendorNo = '';  //选择国家时清空厂号
      },

      // 产地厂号二级选择控件
      openVendorPicker() {
        this.isShowVendorPicker = true;
      },
      closeVendorPicker() {
        this.isShowVendorPicker = false;
      },
      selectedVendor(countryOrigin, vendorNo) {
        this.data.countryOrigin = countryOrigin;
        this.data.vendorNo = vendorNo;
      },
      // 省份城市二级选择控件
      openCityPicker() {
        this.isShowCityPicker = true;
      },
      closeCityPicker() {
        this.isShowCityPicker = false;
      },
      selectedCity(province, city) {
        this.data.province = province;
        this.data.city = city;
      },

      checkWeight() {
        var value = this.data.weight;
        var res= validate.checkWeight(null, value);
        if (res==true) {
          return true;
        }else{
          uni.showToast({
            icon: 'none',
            title: res
          })
          return false;
        }
      },
      onCheckbox() {
        let that = this;
        if (that.isCheckbox) {
          that.isCheckbox = false;
        } else {
          that.isCheckbox = true;
        }
      },
      clearData() {
        this.data.goodsName = '',
            this.data.countryOrigin = '',
            this.data.intentPriceBottom = '',
            this.data.intentPriceTop = '',
            this.data.vendorNo = '',
            this.data.province = '',
            this.data.city = '',
            this.data.weight = '',
            this.data.remarkDemand = ''
      },
      //保存formid
      saveFormId(e) {
        let that = this;
        that.commonSaveFormId(e)//保存表单FormId
      },
    }
  }
</script>
<style>

    .page-body {
        background: #F2F2F5;
        width: 100vw;
        min-height: 100vh;


    }

    .page-body-box {
        background: #F2F2F5;
        margin-left: 24upx;
        margin-right: 24upx;
        padding-top: 20upx;
    }

    .buyinfo-box {
        display: flex;
        justify-content: flex-start;
        padding-top: 20upx;
        z-index: 1;
        background: #FFFFFF;

    }

    .buyinfo-row-text {
        height: 80upx;
        line-height: 80upx;
        padding-left: 20upx;
        font-size: 28upx;
        color: #1A1A1A;
        padding-right: 34upx;
        width: 120upx;
        text-algin:text-justify;

    }
    .letter-spacing{
        letter-spacing: 3upx;
    }


    .buyinfo-row-input {
        height: 80upx;
        line-height: 80upx;
        border: #E5E5E5 1upx solid;
        border-radius: 8upx;
        width: 508upx;
        text-align: right;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .buyinfo-row-input view {
        font-size: 28upx;
        padding-left: 20upx;
    }

    .buyinfo-row-input image {
        width: 36upx;
        height: 36upx;
        margin-right: 10upx;
        transform: rotate(90deg);
    }

    .buyinfo-row-input-unit {
        font-size: 28upx;
        margin-right: 20upx;

    }

    .buyinfo-row2-text {
        width: 160upx;
        padding-left: 20upx;
        height: 80upx;
        line-height: 80upx;
        border-radius: 8upx;
        border: #E5E5E5 1upx solid;

    }

    .select-default {
        color: #B2B2B2;
        font-size: 28upx;
    }

    .buyinfo-row2-text-line {
        width: 25upx;
        text-align: center;

    }

    .buyinfo-row2-input {
        display: flex;
        font-size: 28upx;
        color: #1A1A1A;
        justify-content: center;
        height: 80upx;
        line-height: 80upx;

    }

    .buyinfo-row2-text-pro {
        padding-left: 10upx;
        font-size: 28upx;
    }

    .buyinfo-checkbox {
        display: flex;
        justify-content: center;
        padding-bottom: 20upx;
        padding-left: 20upx;
        padding-right: 24upx;
        height: 110upx;
        margin-top: 20upx;

        background: #FFFFFF;
    }

    .buyinfo-checkbox text {
        font-size: 28upx;
        color: #4C4C4C;
        padding-top: 20upx;
    }

    .buyinfo-btn-box button {
        width: 580upx;
        background: #077131;
        color: #FFFFFF;
        font-size: 34upx;
        height: 88upx;
        line-height: 88upx;
        border-radius: 44upx;
        margin-top: 80upx;
    }

    .buyinfo-row-textarea {
        width: 508upx;
        min-height: 150upx;
        border-radius: 8upx;
        border: 1px solid #e5e5e5;
        margin-bottom: 20upx;
        font-size: 28upx;

    }

    .buyinfo-row-textarea textarea {
        height: 170upx;
        padding-left: 20upx;
        padding-top: 20upx;
        width: 468upx;

    }

    .textarea-placeholder {
        color: #B2B2B2;

    }

    .buyinfo-checkbox-btn {
        padding-top: 20upx;
        padding-right: 10upx;

    }

    .buyinfo-checkbox-btn image {

        width: 30upx;
        height: 30upx;
    }

    .buyinfo-checkbox-line16 {
        line-height: 46upx;
    }

    .buyinfo-row-input-text {
        text-align: left;
        width: 100%;
        display: flex;
        justify-content: flex-start;

    }

    .buyinfo-row-input-text input {
        font-size: 28upx;
    }
</style>
